package server

import (
	"github.com/pkg/errors"
	"go_api/model"
	"go_api/pkg/bcrypt"
	"go_api/request"
	"strconv"
	"sync"
)

// 认证单例
type AuthServer struct{}

var (
	authInstance *AuthServer
	authOnce     sync.Once
)

// GetAuthServerInstance 获取单例实例
func GetAuthServerInstance() *AuthServer {
	authOnce.Do(func() {
		authInstance = &AuthServer{}
	})
	return authInstance
}

type UserData struct {
	UId   int    `json:"u_id"`  //员工ID
	Phone string `json:"phone"` //手机号
	Name  string `json:"name"`  //姓名
	Token string `json:"token"` //当前登录token
}

func (a *AuthServer) UserLogin(data request.LoginRequest) (UserData, error) {

	var userData UserData
	userModel := model.XUser{}
	//根据手机号获取用户
	userInfo, err := userModel.GetUserByPhone(data.Phone)
	if err != nil {
		return userData, errors.New("查找失败")
	}
	if userInfo.ID <= 0 {
		return userData, errors.New("用户不存在")
	}

	//密码验证
	passCheck := bcrypt.GetPasswordUtil().Verify(userInfo.Password, data.Password)
	if !passCheck {
		return userData, errors.New("密码错误")
	}
	//重置token
	tokenStr, err := bcrypt.GetPasswordUtil().Encrypt(strconv.Itoa(userInfo.ID))
	if err != nil {
		return userData, errors.New("token生成失败")
	}
	err = userModel.UpdateTxToken(tokenStr)
	if err != nil {
		return userData, err
	}
	//返回数据
	userData.UId = userInfo.ID
	userData.Phone = userInfo.Phone
	userData.Name = userInfo.Name
	userData.Token = userInfo.Name

	return userData, nil
}
